<!doctype html>



  


<html class="theme-next pisces use-motion">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>



<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />












  
  
  <link href="/vendors/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />




  
  
  
  

  
    
    
  

  

  

  

  

  
    
    
    <link href="//fonts.useso.com/css?family=Lato:300,300italic,400,400italic,700,700italic&subset=latin,latin-ext" rel="stylesheet" type="text/css">
  






<link href="/vendors/font-awesome/css/font-awesome.min.css?v=4.4.0" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=5.0.1" rel="stylesheet" type="text/css" />


  <meta name="keywords" content="Dojo,FizzBuzz,Kata,Python,TDD,招式,编程道场," />








  <link rel="shortcut icon" type="image/x-icon" href="/favicon.ico?v=5.0.1" />






<meta name="description" content="Code Dojo:FizzBuzz Kata by python使用TDD解决FizzBuzz问题
　　这是和一群小伙伴玩编程道场，练习一个TDD的KATA时的小题目，这样的形式很有意思，大家的关注力从头到尾都很集中。

问题描述：小朋友玩的一个有意思的游戏，每个人按顺序报数，如果遇到３或者３的倍数则喊：“Fizz”，如果遇到５或者５的倍数则喊：“Buzz”，如果３和５的公倍数则喊：“Fizz">
<meta property="og:type" content="article">
<meta property="og:title" content="编程道场:FizzBuzz">
<meta property="og:url" content="http://www.huangyong.me/2016/05/23/CodeDojo-FizzBuzz/index.html">
<meta property="og:site_name" content="黄勇的技术博客">
<meta property="og:description" content="Code Dojo:FizzBuzz Kata by python使用TDD解决FizzBuzz问题
　　这是和一群小伙伴玩编程道场，练习一个TDD的KATA时的小题目，这样的形式很有意思，大家的关注力从头到尾都很集中。

问题描述：小朋友玩的一个有意思的游戏，每个人按顺序报数，如果遇到３或者３的倍数则喊：“Fizz”，如果遇到５或者５的倍数则喊：“Buzz”，如果３和５的公倍数则喊：“Fizz">
<meta property="og:image" content="http://7xpa6t.com1.z0.glb.clouddn.com/16-6-1/87882963.jpg">
<meta property="og:updated_time" content="2016-06-27T02:15:38.198Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="编程道场:FizzBuzz">
<meta name="twitter:description" content="Code Dojo:FizzBuzz Kata by python使用TDD解决FizzBuzz问题
　　这是和一群小伙伴玩编程道场，练习一个TDD的KATA时的小题目，这样的形式很有意思，大家的关注力从头到尾都很集中。

问题描述：小朋友玩的一个有意思的游戏，每个人按顺序报数，如果遇到３或者３的倍数则喊：“Fizz”，如果遇到５或者５的倍数则喊：“Buzz”，如果３和５的公倍数则喊：“Fizz">



<script type="text/javascript" id="hexo.configuration">
  var NexT = window.NexT || {};
  var CONFIG = {
    scheme: 'Pisces',
    sidebar: {"position":"left","display":"post"},
    fancybox: true,
    motion: true,
    duoshuo: {
      userId: 0,
      author: 'chinesequant'
    }
  };
</script>




  <title> 编程道场:FizzBuzz | 黄勇的技术博客 </title>
</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  


<script>
  (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
            (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
          m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
  })(window,document,'script','//www.google-analytics.com/analytics.js','ga');
  ga('create', 'true', 'auto');
  ga('send', 'pageview');
</script>


  <script type="text/javascript">
    var _hmt = _hmt || [];
    (function() {
      var hm = document.createElement("script");
      hm.src = "//hm.baidu.com/hm.js?bbe1068ce8d9f53dce8df78d0bbb209a";
      var s = document.getElementsByTagName("script")[0];
      s.parentNode.insertBefore(hm, s);
    })();
  </script>








  
  
    
  

  <div class="container one-collumn sidebar-position-left page-post-detail ">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-meta ">
  

  <div class="custom-logo-site-title">
    <a href="/"  class="brand" rel="start">
      <span class="logo-line-before"><i></i></span>
      <span class="site-title">黄勇的技术博客</span>
      <span class="logo-line-after"><i></i></span>
    </a>
  </div>
  <p class="site-subtitle">记录有趣的事情</p>
</div>

<div class="site-nav-toggle">
  <button>
    <span class="btn-bar"></span>
    <span class="btn-bar"></span>
    <span class="btn-bar"></span>
  </button>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />
            
            归档
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br />
            
            标签
          </a>
        </li>
      

      
    </ul>
  

  
</nav>

 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  
  

  
  
  

  <article class="post post-type-normal " itemscope itemtype="http://schema.org/Article">

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">
            
            
              
                编程道场:FizzBuzz
              
            
          </h1>
        

        <div class="post-meta">
          <span class="post-time">
            <span class="post-meta-item-icon">
              <i class="fa fa-calendar-o"></i>
            </span>
            <span class="post-meta-item-text">发表于</span>
            <time itemprop="dateCreated" datetime="2016-05-23T13:28:00+08:00" content="2016年05月23日">
              2016年05月23日
            </time>
          </span>

          

          
            
              <span class="post-comments-count">
                &nbsp; | &nbsp;
                <a href="/2016/05/23/CodeDojo-FizzBuzz/#comments" itemprop="discussionUrl">
                  <span class="post-comments-count ds-thread-count" data-thread-key="2016/05/23/CodeDojo-FizzBuzz/" itemprop="commentsCount"></span>
                </a>
              </span>
            
          

          

          
          

          
        </div>
      </header>
    


    <div class="post-body" itemprop="articleBody">

      
      

      
        <h3 id="Code_Dojo:FizzBuzz_Kata_by_python">Code Dojo:FizzBuzz Kata by python</h3><h3 id="使用TDD解决FizzBuzz问题">使用TDD解决FizzBuzz问题</h3><p><img src="http://7xpa6t.com1.z0.glb.clouddn.com/16-6-1/87882963.jpg" alt=""></p>
<p>　　这是和一群小伙伴玩编程道场，练习一个TDD的KATA时的小题目，这样的形式很有意思，大家的关注力从头到尾都很集中。</p>
<blockquote>
<p>问题描述：<br>小朋友玩的一个有意思的游戏，每个人按顺序报数，如果遇到３或者３的倍数则喊：“Fizz”，如果遇到５或者５的倍数则喊：“Buzz”，如果３和５的公倍数则喊：“Fizz Buzz”</p>
</blockquote>
<a id="more"></a>
<p>梳理一下，需求如下：</p>
<table>
<thead>
<tr>
<th>编号</th>
<th>需求</th>
</tr>
</thead>
<tbody>
<tr>
<td>１</td>
<td>正常情况下报数字</td>
</tr>
<tr>
<td>２</td>
<td>３的倍数时报“Fizz”</td>
</tr>
<tr>
<td>３</td>
<td>５的倍数时报“Buzz”</td>
</tr>
<tr>
<td>４</td>
<td>３和５的公倍数时报“Fizz Buzz”</td>
</tr>
</tbody>
</table>
<p>需求列清楚了，可以从测试开始，使用的是本地化的<a href="http://www.cyber-dojo.org" target="_blank" rel="external">cyber-dojo</a>。</p>
<h3 id="需求１">需求１</h3><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">test_it_should_print_the_number_itself_if_it_is_a_normal_number</span><span class="params">(self)</span>:</span></span><br><span class="line">        <span class="comment"># arrange</span></span><br><span class="line">        fizzbuzz = fizz_buzz_kata.FizzBuzz()</span><br><span class="line"> </span><br><span class="line">        <span class="comment"># act</span></span><br><span class="line">        <span class="comment"># assert</span></span><br><span class="line">        <span class="keyword">assert</span> fizzbuzz.say(<span class="number">1</span>) == <span class="string">"1"</span></span><br></pre></td></tr></table></figure>
<p>为了让测试通过，有了如下的代码：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">FizzBuzz</span>:</span>    </span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">say</span><span class="params">(self,number)</span>:</span></span><br><span class="line">        <span class="keyword">return</span> str(number)</span><br></pre></td></tr></table></figure>
<h3 id="需求2、３、４">需求2、３、４</h3><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">test_it_should_print_fizz_if_it_is_a_number_times_of_three</span><span class="params">(self)</span>:</span></span><br><span class="line">    fizz = fizz_buzz_kata.FizzBuzz()</span><br><span class="line">    self.assertEqual(fizz.say(<span class="number">3</span>),<span class="string">"fizz"</span>)</span><br><span class="line">    self.assertEqual(fizz.say(<span class="number">6</span>),<span class="string">"fizz"</span>)</span><br><span class="line"> </span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">test_it_should_print_buzz_if_it_is_a_number_times_of_five</span><span class="params">(self)</span>:</span></span><br><span class="line">    buzz = fizz_buzz_kata.FizzBuzz()</span><br><span class="line">    self.assertEqual(buzz.say(<span class="number">5</span>),<span class="string">"buzz"</span>)</span><br><span class="line"> </span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">test_it_should_print_fizzbuzz_if_it_is_a_number_times_of_five_and_three</span><span class="params">(self)</span>:</span></span><br><span class="line">    fizzbuzz = fizz_buzz_kata.FizzBuzz()</span><br><span class="line">    self.assertEqual(fizzbuzz.say(<span class="number">15</span>),<span class="string">"fizzbuzz"</span>)</span><br></pre></td></tr></table></figure>
<p>实现：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">FizzBuzz</span>:</span>    </span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">say</span><span class="params">(self,number)</span>:</span></span><br><span class="line">        <span class="keyword">if</span> number % <span class="number">3</span> == <span class="number">0</span> <span class="keyword">and</span> number % <span class="number">5</span> != <span class="number">0</span>:</span><br><span class="line">            <span class="keyword">return</span> <span class="string">"fizz"</span></span><br><span class="line">        <span class="keyword">elif</span> number % <span class="number">5</span> == <span class="number">0</span> <span class="keyword">and</span> number % <span class="number">3</span> != <span class="number">0</span>:</span><br><span class="line">            <span class="keyword">return</span> <span class="string">"buzz"</span></span><br><span class="line">        <span class="keyword">elif</span> number % <span class="number">5</span> == <span class="number">0</span> <span class="keyword">and</span> number % <span class="number">3</span> == <span class="number">0</span>:</span><br><span class="line">            <span class="keyword">return</span> <span class="string">"fizzbuzz"</span></span><br><span class="line">        <span class="keyword">else</span>:</span><br><span class="line">            <span class="keyword">return</span> str(number)</span><br></pre></td></tr></table></figure>
<h3 id="识别坏味道">识别坏味道</h3><p>最明显的坏味道就是say函数，典型的Golden function。</p>
<ul>
<li>条件语句太多，但不能清晰地表明它的语义。</li>
<li>return语句返回的内容和条件语句密切相关。</li>
<li>大量的 <strong>if elif</strong> 使得让我感觉这里需要应用某个模式。</li>
</ul>
<p>首先来解决第一个问题，通常的办法是把条件语句提取成命名函数，来起到强化语义的作用。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">FizzBuzz</span>:</span>    </span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">say</span><span class="params">(self,number)</span>:</span></span><br><span class="line">        <span class="keyword">if</span> isFizz(number):</span><br><span class="line">            <span class="keyword">return</span> <span class="string">"fizz"</span></span><br><span class="line">        <span class="keyword">elif</span> isBuzz(number):</span><br><span class="line">            <span class="keyword">return</span> <span class="string">"buzz"</span></span><br><span class="line">        <span class="keyword">elif</span> isFizzBuzz(number):</span><br><span class="line">            <span class="keyword">return</span> <span class="string">"fizzbuzz"</span></span><br><span class="line">        <span class="keyword">else</span>:</span><br><span class="line">            <span class="keyword">return</span> str(number)</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">isFizz</span><span class="params">(number)</span>:</span></span><br><span class="line">    <span class="keyword">return</span> number % <span class="number">3</span> == <span class="number">0</span> <span class="keyword">and</span> number % <span class="number">5</span> != <span class="number">0</span></span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">isBuzz</span><span class="params">(number)</span>:</span></span><br><span class="line">    <span class="keyword">return</span> number % <span class="number">5</span> == <span class="number">0</span> <span class="keyword">and</span> number % <span class="number">3</span> != <span class="number">0</span>:</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">isFizzBuzz</span><span class="params">(number)</span>:</span></span><br><span class="line">    <span class="keyword">return</span> number % <span class="number">5</span> == <span class="number">0</span> <span class="keyword">and</span> number % <span class="number">3</span> == <span class="number">0</span></span><br></pre></td></tr></table></figure>
<p>这样重构后，迅速跑通所有的测试，没有改变我们代码的外部行为，但条件语句的语义信息已经足够清晰了。<br>接下来是第二个坏味道，不难得出，条件语句与返回值是一一对应的，如果这样的好基友出现在代码里，我们首先考虑的是让他们在一起。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br></pre></td><td class="code"><pre><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">FizzBuzz</span>:</span>    </span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">__init__</span><span class="params">(self)</span>:</span></span><br><span class="line">        self.handleFizz = HandleFizz()</span><br><span class="line">        self.handleBuzz = HandleBuzz()</span><br><span class="line">        self.handleFizzBuzz = HandleFizzBuzz()</span><br><span class="line">        self.handleNormalNumber = HandleNumber()</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">say</span><span class="params">(self,number)</span>:</span></span><br><span class="line">        <span class="keyword">if</span> self.handleFizz.isFizz(number):</span><br><span class="line">            <span class="keyword">return</span> self.handlefizz.say(number)</span><br><span class="line">        <span class="keyword">elif</span> self.handleBuzz.isBuzz(number):</span><br><span class="line">            <span class="keyword">return</span> self.handleBuzz.say(number)</span><br><span class="line">        <span class="keyword">elif</span> self.handleFizzBuzz.isFizzBuzz(number):</span><br><span class="line">            <span class="keyword">return</span> self.handleFizzBuzz.say(number)</span><br><span class="line">        <span class="keyword">else</span>:</span><br><span class="line">            <span class="keyword">return</span> self.handleNormalNumber.say(number)</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">HandleFizz</span>:</span></span><br><span class="line">   <span class="function"><span class="keyword">def</span> <span class="title">isFizz</span><span class="params">(self, number)</span>:</span></span><br><span class="line">       <span class="keyword">return</span> number % <span class="number">3</span> == <span class="number">0</span> <span class="keyword">and</span> number % <span class="number">5</span> != <span class="number">0</span></span><br><span class="line"></span><br><span class="line">   <span class="function"><span class="keyword">def</span> <span class="title">say</span><span class="params">(self, number)</span>:</span></span><br><span class="line">       <span class="keyword">return</span> <span class="string">"fizz"</span></span><br><span class="line"> </span><br><span class="line"> </span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">HandleBuzz</span>:</span></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">isBuzz</span><span class="params">(self, number)</span>:</span></span><br><span class="line">        <span class="keyword">return</span> number % <span class="number">5</span> == <span class="number">0</span> <span class="keyword">and</span> number % <span class="number">3</span> != <span class="number">0</span>:</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">say</span><span class="params">(self, number)</span>:</span></span><br><span class="line">        <span class="keyword">return</span> <span class="string">"buzz"</span></span><br><span class="line"> </span><br><span class="line"> </span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">FizzBuzz</span>:</span></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">isFizzBuzz</span><span class="params">(self, number)</span>:</span></span><br><span class="line">        <span class="keyword">return</span> number % <span class="number">5</span> == <span class="number">0</span> <span class="keyword">and</span> number % <span class="number">3</span> == <span class="number">0</span></span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">say</span><span class="params">(self,number)</span>:</span></span><br><span class="line">        <span class="keyword">return</span> <span class="string">"fizzbuzz"</span></span><br><span class="line"> </span><br><span class="line"> </span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">NormalNumber</span>:</span></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">say</span><span class="params">(self, number)</span>:</span></span><br><span class="line">        <span class="keyword">return</span> str(number)</span><br></pre></td></tr></table></figure>
<p>最后就只剩下这个长长的条件判断结构让我们不爽了。<br>过多的条件判断会让代码的语义难以理解，如此长的逻辑流通常也是容易出错的地方。我们需要梳理一下，套用某种模式来管理这样的复杂多。过多的条件判断一般会考虑两种模式：</p>
<ul>
<li>State</li>
<li>Chain of Responsibility</li>
</ul>
<p>　　前者的应用场景是长长的条件判断来控制对象的状态；而后者的应用场景是长长的条件语句来控制对同一数据的不同处理。显然，我们的场景需要职责链模型。</p>
<blockquote>
<p>使多个对象都有机会处理请求，从而避免请求的发送者和接收者之间的耦合关系。将这个对象连成一条链，并沿着这条链传递该请求，直到一个对象处理它为止。</p>
</blockquote>
<p>其实，经过上面的重构，此时的职责链已经呼之欲出了,直接给出代码。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br></pre></td><td class="code"><pre><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Fizzbuzz</span>:</span></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">say</span><span class="params">(self, num)</span>:</span></span><br><span class="line">        handleNormal = HandleNormal(<span class="keyword">None</span>)</span><br><span class="line">        handleBuzz = HandleBuzz(handleNormal)</span><br><span class="line">        handleFizz = HandleFizz(handleBuzz)</span><br><span class="line">        handleFizzBuzz = HandleFizzBuzz(handleFizz)</span><br><span class="line">        result = handleFizzBuzz.say(num)</span><br><span class="line">        <span class="keyword">return</span> result</span><br><span class="line"> </span><br><span class="line">  </span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Handler</span>:</span></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">__init__</span><span class="params">(self, _successor)</span>:</span></span><br><span class="line">        self.successor = _successor</span><br><span class="line"> </span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">doSuccessor</span><span class="params">(self, num)</span>:</span></span><br><span class="line">        <span class="keyword">if</span> self.successor <span class="keyword">is</span> <span class="keyword">not</span> <span class="keyword">None</span>:</span><br><span class="line">            <span class="keyword">return</span> self.successor.say(num)</span><br><span class="line"> </span><br><span class="line"> </span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">HandleFizzBuzz</span><span class="params">(Handler)</span>:</span></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">isMyWay</span><span class="params">(self, num)</span>:</span></span><br><span class="line">        <span class="keyword">return</span> (num % <span class="number">3</span> == <span class="number">0</span>) <span class="keyword">and</span> (num % <span class="number">5</span> ==<span class="number">0</span>)</span><br><span class="line"> </span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">say</span><span class="params">(self, num)</span>:</span></span><br><span class="line">        <span class="keyword">if</span> self.isMyWay(num):</span><br><span class="line">            <span class="keyword">return</span> <span class="string">"fizzbuzz"</span></span><br><span class="line">        <span class="keyword">return</span> self.doSuccessor(num)</span><br><span class="line">            </span><br><span class="line"> </span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">HandleFizz</span><span class="params">(Handler)</span>:</span></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">isMyWay</span><span class="params">(self, num)</span>:</span></span><br><span class="line">        <span class="keyword">return</span> (num % <span class="number">3</span> == <span class="number">0</span>)</span><br><span class="line"> </span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">say</span><span class="params">(self, num)</span>:</span></span><br><span class="line">        <span class="keyword">if</span> self.isMyWay(num):</span><br><span class="line">            <span class="keyword">return</span> <span class="string">"fizz"</span></span><br><span class="line">        <span class="keyword">elif</span> self.successor <span class="keyword">is</span> <span class="keyword">not</span> <span class="keyword">None</span>:</span><br><span class="line">            <span class="keyword">return</span> self.successor.say(num)</span><br><span class="line"> </span><br><span class="line"> </span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">HandleBuzz</span><span class="params">(Handler)</span>:</span></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">isMyWay</span><span class="params">(self, num)</span>:</span></span><br><span class="line">        <span class="keyword">return</span> (num % <span class="number">5</span> ==<span class="number">0</span>)</span><br><span class="line"> </span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">say</span><span class="params">(self, num)</span>:</span></span><br><span class="line">        <span class="keyword">if</span> self.isMyWay(num):</span><br><span class="line">            <span class="keyword">return</span> <span class="string">"buzz"</span></span><br><span class="line">        <span class="keyword">elif</span> self.successor <span class="keyword">is</span> <span class="keyword">not</span> <span class="keyword">None</span>:</span><br><span class="line">            <span class="keyword">return</span> self.successor.say(num)</span><br><span class="line"> </span><br><span class="line"> </span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">HandleNormal</span><span class="params">(Handler)</span>:</span></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">say</span><span class="params">(self, num)</span>:</span></span><br><span class="line">        <span class="keyword">return</span> str(num)</span><br></pre></td></tr></table></figure>
<p>　　当然了，当场有小伙子们提出了可以将职责链处理里向下转移的部分提取到Handler类当中去，我觉得也可以，主要看应用场景。如果考虑到以后会有更复杂的转移条件，则目前这样的状态好一些；如果转移场景比较固定，进一步提取，也不失为一个好方法。</p>

      
    </div>

    <div>
      
        
<div id="wechat_subscriber" style="display: block； padding: 10px 0; margin: 20px auto; width: 100%; text-align: center">
    <img id="wechat_subscriber_qcode" src="http://7xpa6t.com1.z0.glb.clouddn.com/wechat.jpg" alt="tony wechat" style="width: 200px; max-width: 100%;"/>
    <div>欢迎添加微信与我交流！</div>
</div>

      
    </div>

    <div>
      
        
  <div style="padding: 10px 0; margin: 20px auto; width: 90%; text-align: center;">
    <div>坚持分享，您的支持将鼓励我继续创作。</div>
    <button id="rewardButton" disable="enable" onclick="var qr = document.getElementById('QR'); if (qr.style.display === 'none') {qr.style.display='block';} else {qr.style.display='none'}">
      <span>赏</span>
    </button>
    <div id="QR" style="display: none;">
      
        <div id="wechat" style="display: inline-block">
          <img id="wechat_qr" src="http://7xpa6t.com1.z0.glb.clouddn.com/wechat_pay.jpg" alt="tony WeChat Pay"/>
          <p>微信打赏</p>
        </div>
      
      
        <div id="alipay" style="display: inline-block">
          <img id="alipay_qr" src="http://7xpa6t.com1.z0.glb.clouddn.com/alipay.jpg" alt="tony Alipay"/>
          <p>支付宝打赏</p>
        </div>
      
    </div>
  </div>


      
    </div>

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/Dojo/" rel="tag">#Dojo</a>
          
            <a href="/tags/FizzBuzz/" rel="tag">#FizzBuzz</a>
          
            <a href="/tags/Kata/" rel="tag">#Kata</a>
          
            <a href="/tags/Python/" rel="tag">#Python</a>
          
            <a href="/tags/TDD/" rel="tag">#TDD</a>
          
            <a href="/tags/招式/" rel="tag">#招式</a>
          
            <a href="/tags/编程道场/" rel="tag">#编程道场</a>
          
        </div>
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2016/05/19/九宫格访谈/" rel="next" title="九宫格访谈">
                <i class="fa fa-chevron-left"></i> 九宫格访谈
              </a>
            
          </div>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2016/06/12/编程道场-Conway-Game/" rel="prev" title="编程道场:Conway Game">
                编程道场:Conway Game <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </article>



    <div class="post-spread">
      
        <!-- JiaThis Button BEGIN -->
<div class="jiathis_style">
  <a class="jiathis_button_tsina"></a>
  <a class="jiathis_button_tqq"></a>
  <a class="jiathis_button_weixin"></a>
  <a class="jiathis_button_cqq"></a>
  <a class="jiathis_button_douban"></a>
  <a class="jiathis_button_renren"></a>
  <a class="jiathis_button_qzone"></a>
  <a class="jiathis_button_kaixin001"></a>
  <a class="jiathis_button_copy"></a>
  <a href="http://www.jiathis.com/share" class="jiathis jiathis_txt jiathis_separator jtico jtico_jiathis" target="_blank"></a>
  <a class="jiathis_counter_style"></a>
</div>
<script type="text/javascript" >
  var jiathis_config={
    hideMore:false
  }
</script>
<script type="text/javascript" src="http://v3.jiathis.com/code/jia.js" charset="utf-8"></script>
<!-- JiaThis Button END -->

      
    </div>
  </div>


          </div>
          


          
  <div class="comments" id="comments">
    
      <div class="ds-thread" data-thread-key="2016/05/23/CodeDojo-FizzBuzz/"
           data-title="编程道场:FizzBuzz" data-url="http://www.huangyong.me/2016/05/23/CodeDojo-FizzBuzz/">
      </div>
    
  </div>


        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap" >
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview sidebar-panel ">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
          <img class="site-author-image" itemprop="image"
               src="http://ww4.sinaimg.cn/mw690/7ecfc119jw8et76rgrm1kj20k00k00vi.jpg"
               alt="tony" />
          <p class="site-author-name" itemprop="name">tony</p>
          <p class="site-description motion-element" itemprop="description"></p>
        </div>
        <nav class="site-state motion-element">
          <div class="site-state-item site-state-posts">
            <a href="/archives">
              <span class="site-state-item-count">14</span>
              <span class="site-state-item-name">日志</span>
            </a>
          </div>

          
            <div class="site-state-item site-state-categories">
              
                <span class="site-state-item-count">1</span>
                <span class="site-state-item-name">分类</span>
              
            </div>
          

          
            <div class="site-state-item site-state-tags">
              <a href="/tags">
                <span class="site-state-item-count">35</span>
                <span class="site-state-item-name">标签</span>
              </a>
            </div>
          

        </nav>

        

        <div class="links-of-author motion-element">
          
            
              <span class="links-of-author-item">
                <a href="https://github.com/Tony-Wang" target="_blank" title="github">
                  
                    <i class="fa fa-fw fa-github"></i>
                  
                  github
                </a>
              </span>
            
              <span class="links-of-author-item">
                <a href="http://weibo.com/u/2127544601" target="_blank" title="微博">
                  
                    <i class="fa fa-fw fa-weibo"></i>
                  
                  微博
                </a>
              </span>
            
              <span class="links-of-author-item">
                <a href="http://www.zhihu.com/people/huangyong.me" target="_blank" title="知乎">
                  
                    <i class="fa fa-fw fa-paper-plane"></i>
                  
                  知乎
                </a>
              </span>
            
              <span class="links-of-author-item">
                <a href="mailto:tony@huangyong.me" target="_blank" title="mail">
                  
                    <i class="fa fa-fw fa-envelope-o"></i>
                  
                  mail
                </a>
              </span>
            
          
        </div>

        
        

        
        

      </section>

      
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">
            
              
            
            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-3"><a class="nav-link" href="#Code_Dojo:FizzBuzz_Kata_by_python"><span class="nav-number">1.</span> <span class="nav-text">Code Dojo:FizzBuzz Kata by python</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#使用TDD解决FizzBuzz问题"><span class="nav-number">2.</span> <span class="nav-text">使用TDD解决FizzBuzz问题</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#需求１"><span class="nav-number">3.</span> <span class="nav-text">需求１</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#需求2、３、４"><span class="nav-number">4.</span> <span class="nav-text">需求2、３、４</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#识别坏味道"><span class="nav-number">5.</span> <span class="nav-text">识别坏味道</span></a></li></ol></div>
            
          </div>
        </section>
      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright" >
  
  &copy; 
  <span itemprop="copyrightYear">2017</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">tony</span>
</div>

<div class="powered-by">
  由 <a class="theme-link" href="http://hexo.io">Hexo</a> 强力驱动
</div>

<div class="theme-info">
  主题 -
  <a class="theme-link" href="https://github.com/iissnan/hexo-theme-next">
    NexT.Pisces
  </a>
</div>

        

        
      </div>
    </footer>

    <div class="back-to-top">
      <i class="fa fa-arrow-up"></i>
    </div>
  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  



  
  <script type="text/javascript" src="/vendors/jquery/index.js?v=2.1.3"></script>

  
  <script type="text/javascript" src="/vendors/fastclick/lib/fastclick.min.js?v=1.0.6"></script>

  
  <script type="text/javascript" src="/vendors/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>

  
  <script type="text/javascript" src="/vendors/velocity/velocity.min.js?v=1.2.1"></script>

  
  <script type="text/javascript" src="/vendors/velocity/velocity.ui.min.js?v=1.2.1"></script>

  
  <script type="text/javascript" src="/vendors/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.0.1"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.0.1"></script>



  
  


  <script type="text/javascript" src="/js/src/affix.js?v=5.0.1"></script>

  <script type="text/javascript" src="/js/src/schemes/pisces.js?v=5.0.1"></script>



  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.0.1"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.0.1"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.0.1"></script>



  

  
    
  

  <script type="text/javascript">
    var duoshuoQuery = {short_name:"chinesequant"};
    (function() {
      var ds = document.createElement('script');
      ds.type = 'text/javascript';ds.async = true;
      ds.id = 'duoshuo-script';
      ds.src = (document.location.protocol == 'https:' ? 'https:' : 'http:') + '//static.duoshuo.com/embed.js';
      ds.charset = 'UTF-8';
      (document.getElementsByTagName('head')[0]
      || document.getElementsByTagName('body')[0]).appendChild(ds);
    })();
  </script>

  
    
      
      <script src="/vendors/ua-parser-js/dist/ua-parser.min.js?v=0.7.9"></script>
      <script src="/js/src/hook-duoshuo.js"></script>
    
  






  
  
  

  

  
<script type="text/javascript" async src="//push.zhanzhang.baidu.com/push.js">
</script>


</body>
</html>
